<template>
    <div>
        <navigation-bar>
            <div class="searchContent">
                <el-input v-model="unitName" placeholder="请输入机构名称" size="mini" style="width: 150px; margin-right: 10px"></el-input>
                <custom-button type="search" style="margin-right: 10px" @searchClick="searchClick"></custom-button>
                <custom-button type="reset" style="margin-right: 10px" @resetClick="resetClick"></custom-button>
                <custom-button type="add" style="margin-right: 10px" @addClick="addClick"></custom-button>
                <custom-button
                    type="custom"
                    title="启用"
                    icon="el-icon-edit"
                    style="margin-right: 10px"
                    @customClick="customClick(false)"
                ></custom-button>
                <custom-button
                    type="custom"
                    title="禁用"
                    icon="el-icon-edit"
                    style="margin-right: 10px"
                    @customClick="customClick(true)"
                ></custom-button>
                <custom-button type="custom" title="审核" icon="el-icon-check" @customClick="checkData"></custom-button>
            </div>
        </navigation-bar>

        <div style="margin-top: 10px">
            <table-index
                :dataSource="dataSource"
                :tableColumns="tableColumns"
                :btnList="btnList"
                :pageSize="pageSize"
                :pageCount="pageCount"
                :pageNo="pageNo"
                @pageChange="pageChange"
                @editRow="editRow"
                @viewRow="viewRow"
                @deleteRow="deleteRow"
                selection
                @handleSelectionChange="handleSelectionChange"
                :height="secondTableHeight"
            ></table-index>
        </div>

        <div v-if="dialogShow">
            <custom-dialog :title="dialogTitle" size="large" @dialogClose="dialogClose">
                <form-index :formConfig="formConfig" @submit="submit" :type="type" @formInputChange="formInputChange" ref="form">
                    <!--  <div>这里还可以插入其它内容进行拓展</div> -->
                </form-index>
            </custom-dialog>
        </div>
    </div>
</template>

<script>
import {enterpriseOrgForm} from '@/assets/form/managementCenter/systemManage/enterpriseOrg'
import customDialog from '@/components/customComponents/customDialog'
import customButton from '@/components/customComponents/customForm/customButton'
import formIndex from '@/components/customComponents/customForm/formIndex'
import tableIndex from '@/components/customComponents/customeTable/iviewTable/singleViewTable'
import navigationBar from '@/components/customComponents/managementCenter/navigationBar'
import {AjaxCommon, printAddress} from '@/libs/apiCommon'
import {CardId} from '@/libs/cardId'
import {PopupCommon} from '@/libs/popupCommon'
import {SessionCommon} from '@/libs/sessionCommon'
import {Utility} from '@/libs/utility'
import {OrgList} from '@/mockData/systemManage.js'
export default {
    components: {
        navigationBar,
        customButton,
        tableIndex,
        customDialog,
        formIndex
    },
    data() {
        return {
            secondTableHeight: document.body.clientHeight - 270,
            selectOrgList: [],
            unitName: null,
            status: '',
            statusList: Utility.getDictList('status'),
            // table 相关参数  begin
            dataSource: [],
            tableColumns: [
                //                     {
                //   "org_guid": "sample string 1",
                //   "org_full_name": "sample string 2", // 组织机构名称
                //   "org_id": "sample string 3", // 组织机构代码
                //   "org_name": "sample string 4", // 组织机构简称
                //   "USER_NAME": "sample string 5", // 登录用户名
                //   "contracts": "sample string 6", // 联系人
                //   "org_type": "sample string 7", // 机构性质，字典表对应
                //   "user_sex": 8, // 用户性别 0女  1男
                //   "user_tel": "sample string 9", // 手机号码
                //   "user_email": "sample string 10", // 用户邮箱
                //   "org_Remarks": "sample string 11", // 备注
                //   "new_pass": "sample string 12"  // 密码需包含数字、字母及至少一个特殊字符
                // }
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    type: 'index',
                    width: 60,
                    align: 'center'
                },
                {
                    key: 'fullName',
                    title: '组织机构名称'
                },
                {
                    key: 'name',
                    title: '组织机构简称'
                },
                {
                    key: 'orgId',
                    title: '组织机构代码'
                },
                {
                    key: 'dic_DESC',
                    title: '机构性质'
                },
                // {
                //     key: 'USER_NAME',
                //     title: '登录用户名'
                // },
                // {
                //     key: 'new_pass',
                //     title: '登录密码'
                // },

                // {
                //     key: 'contracts',
                //     title: '联系人'
                // },
                // {
                //     key: 'user_tel',
                //     title: '联系方式'
                // },
                // {
                //     key: 'user_sex',
                //     title: '性别'
                // },
                // {
                //     key: 'user_email',
                //     title: '用户邮箱'
                // },
                // {
                //     key: 'remark',
                //     title: '备注'
                // }
                {
                    key: 'isApproval',
                    title: '审核状况',
                    slot: 'isApproval'
                },
                {
                    key: 'isEnable',
                    title: '是否启用',
                    slot: 'isEnable'
                },

                {
                    title: '操作',
                    slot: 'action',
                    width: 120,
                    align: 'center'
                }
            ],
            btnList: ['edit', 'delete'],
            pageSize: 20,
            pageCount: 100,
            pageNo: 1,
            // table 相关参数  end

            // 弹窗是否显示
            dialogShow: false,
            // 弹窗标题 (新增修改不同)
            dialogTitle: '',

            // form的配置信息
            formConfig: null,
            type: 'add',

            typeCodeList: []
        }
    },
    created() {
        Utility.getDictListByTypeCode('ORG_TYPE').then((res) => {
            if (res && res.length > 0) {
                const data = res.map((t) => {
                    return {
                        value: t.value,
                        label: t.desc
                    }
                })
                this.typeCodeList = data
                this.formConfig = enterpriseOrgForm(data, 'add')
            }
        })
    },
    methods: {
        checkData() {
            if (this.selectOrgList.length < 1) {
                PopupCommon.notify('info', '请至少选择一个审核状态未通过的机构')
                return
            }
            // isApproval
            const ids = this.selectOrgList
                .filter((t) => t.isApproval != '1')
                ?.map((t) => t.id)
                .toString()

            if (ids) {
                AjaxCommon('/api/OrgSysManage/AuditingOrgs', 'post', {
                    orgids: ids
                }).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '审核成功')
                        self.initPage()
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            } else {
                PopupCommon.notify('info', '请至少选择一个审核状态未通过的机构')
            }
        },
        getHeight() {
            this.secondTableHeight = document.body.clientHeight - 270
        },
        customClick(isTrue) {
            this.useOrg(isTrue)
        },
        handleSelectionChange(d) {
            this.selectOrgList = d
        },
        printClick() {
            console.log(1111)
            let urlAdd = `${printAddress}/ccdc/tmrreport/pdf/show?1=1&_u=file:shebeibqV1.tmrreport.xml&_i=1&_r=1
`
            if (this.selectOrgList.length > 0) {
                let ids = this.selectOrgList
                    .map((t) => {
                        return t.id
                    })
                    .join(',')
                if (this.selectOrgList.length < 2) {
                    urlAdd += '&id=' + ids
                } else {
                    urlAdd += '&ids=' + ids
                }
            }
            console.log(urlAdd)
            window.open(urlAdd)
        },
        formInputChange(e) {
            if (e.filedName == 'idCard') {
                const data = CardId.getInfoByCardId(e.value)
                if (data) {
                    let newData = e.allData
                    newData['birthday'] = data.birthday
                    newData['sex'] = data.sex
                    this.$refs.form.changeFormValue(newData)
                }
            }
        },
        submit(d) {
            let self = this
            if (d.org_guid) {
                let url = '/api/OrgSysManage/EditCompanyOrg'
                AjaxCommon(url, 'post', d).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '编辑成功')
                        self.initPage()
                        self.dialogClose()
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            } else {
                delete d.org_guid
                // 根据类型调用不同接口
                let url = '/api/OrgSysManage/AddCompanyOrg'
                AjaxCommon(url, 'post', d).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '新增成功')
                        self.initPage()
                        self.dialogClose()
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            }
        },
        dialogClose() {
            this.dialogShow = false
        },
        searchClick() {
            this.pageNo = 1
            this.initPage()
        },
        resetClick() {
            this.unitName = null
            this.searchClick()
        },
        addClick() {
            let formConfigItem = this.formConfig
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    // 用户性别默认男
                    if (t.fieldName == 'user_sex') {
                        t.filedValue = 1
                    } else {
                        t.filedValue = ''
                    }
                })
            })
            this.formConfig = formConfigItem
            this.type = 'add'
            this.dialogTitle = '新增'
            this.dialogShow = true
        },
        // 分页点击事件
        pageChange(p) {
            this.pageNo = p
            this.initPage()
        },
        async editRow(d) {
            this.formConfig = enterpriseOrgForm(this.typeCodeList, 'edit')
            // 先获取组织机构的用户信息
            const userData = await AjaxCommon(`/api/OrgSysManage/GetOrgInfo?org_guid=${d.id}`, 'get', null)
            const newUser = userData?.data?.Message
            this.type = 'edit'
            let formConfigItem = this.formConfig
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    if (t.fieldName == 'org_guid') {
                        t.filedValue = d['id']
                    } else if (t.fieldName == 'org_full_name') {
                        t.filedValue = d['fullName']
                    } else if (t.fieldName == 'org_name') {
                        t.filedValue = d['name']
                    } else if (t.fieldName == 'org_id') {
                        t.filedValue = d['orgId']
                    } else if (t.fieldName == 'org_type') {
                        // 离谱的返回，有个org_type值为1，org_type2又是正确的
                        t.filedValue = d['orgType2']
                    } else if (t.fieldName == 'contracts') {
                        t.filedValue = newUser?.adminName
                    } else if (t.fieldName == 'user_tel') {
                        t.filedValue = newUser?.adminTel
                    } else if (t.fieldName == 'user_sex') {
                        t.filedValue = newUser?.gender
                    } else if (t.fieldName == 'user_email') {
                        t.filedValue = newUser?.email
                    } else if (t.fieldName == 'org_Remarks') {
                        t.filedValue = newUser?.remark
                    }
                })
            })
            this.formConfig = formConfigItem
            this.dialogTitle = '编辑'
            this.dialogShow = true
        },
        viewRow(d) {
            this.type = 'look'
            let formConfigItem = this.formConfig
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    if (res == 'fieldName') {
                        t.filedValue = d.data[t[res]]
                    }
                })
            })
            this.formConfig = formConfigItem
            this.dialogTitle = '查看'
            this.dialogShow = true
        },
        // 启用或禁用组织机构 isTrue  true禁用 false 不禁用
        useOrg(isTrue) {
            const selectOrgList = this.selectOrgList
            if (selectOrgList.length < 1) {
                PopupCommon.notify('info', '请选择至少一个机构')
                return
            }
            const id = selectOrgList.map((t) => t.id).toString()
            let self = this
            let apiUrl = ''
            let tipMsg = ''
            if (!isTrue) {
                apiUrl = `api/OrgSysManage/ChangeOrgsDisable`
                tipMsg = '启用'
            } else {
                apiUrl = 'api/OrgSysManage/ChangeOrgsEnable'
                tipMsg = '禁用'
            }
            AjaxCommon(apiUrl, 'post', {orgids: id}).then((res) => {
                console.log(res, 'res...............')
                if (res?.data?.Code == 200) {
                    PopupCommon.notify('success', tipMsg + '成功')
                    self.initPage()
                } else {
                    const msg = res?.data?.Message
                    if (msg) {
                        PopupCommon.notify('error', msg)
                    }
                }
            })
        },
        deleteRow(d) {
            const id = d.id
            let self = this
            AjaxCommon(`/api/OrgSysManage/DeleteOrgs`, 'post', {orgids: id}).then((res) => {
                console.log(res, 'res...............')
                if (res?.data?.Code == 200) {
                    PopupCommon.notify('success', '删除成功')
                    self.initPage()
                } else {
                    const msg = res?.data?.Message
                    if (msg) {
                        PopupCommon.notify('error', msg)
                    }
                }
            })
        },
        // 初始化事件
        initPage() {
            let self = this
            // &OrgName=${this.unitName}
            let params = `?PageSize=${this.pageSize}&PageIndex=${this.pageNo}&orgType=1`
            if (this.unitName) {
                params += `&OrgName=${this.unitName}`
            }
            AjaxCommon(`/api/OrgSysManage/GetOrgPageDatas${params}`, 'get', null).then((res) => {
                console.log(res, 'res...........')
                if (res?.data?.Code == 200) {
                    const data = res?.data.Message
                    console.log(data?.rows, 'data?.rows...')
                    self.dataSource = data?.rows
                    self.pageCount = parseInt(data?.total)
                } else {
                    PopupCommon.notify('error', res?.data?.msg)
                }
            })
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.getHeight()
            this.initPage()
        })

        /*窗口自适应，关键代码*/
        window.onresize = () => {
            this.getHeight()
        }
    }
}
</script>

<style></style>
